var fs = require('fs');
var path = require('path');
var UPYUN = require('upyun');
var async = require('async');
var request = require('request');

var upyunConfig = require('../config/upyunConfig');

/**
 *下载上传微信图片到UPYUN
 *images array 图片名称
 *dest 目标位置
 *src 源文件位置
 *callback(err, result)
 */
exports.pushWXPic = function(images, dest, src, callback) {
	var upyun = new UPYUN(upyunConfig.bucket, upyunConfig.operator,
		upyunConfig.password, upyunConfig.endpoint, upyunConfig.apiVersion);
 	var loop = 0;
 	var type = 'imgae/jpeg';
 	var successCount = 0;
 	var successImg = [];
 	var writer, url;

 	fs.existsSync('./uploads/temper/') || fs.mkdirSync('./uploads/temper/');
 	
 	var uploadFile = function(imgName, cb) {
 		var remotePath = dest + '/' + imgName;
 		var localFile = './uploads/temper/' + imgName;
 		upyun.uploadFile(remotePath, localFile, type, true, {mkdir: true}, function(err, data) {
			if (err) {
				console.log(err);
				cb(err);
			} else {
				if (data.statusCode == 200) {
					successCount++;
					successImg.push(remotePath);
					//删除本地缓存文件
					fs.unlink(localFile,function(err,data){});
					cb(null);
				} else {
					console.log(data.error);
					cb({msg: data.error});
				}
			}
		})
 	}
 	async.whilst(
 		function() {
 			return loop<images.length;
 		},
 		function(wayneCallback) {
 			var imgName = 'temper-'+ Date.now() +'.png'
 			url = src + images[loop];
 			writer = fs.createWriteStream('./uploads/temper/' + imgName);
 			writer.on('finish', function() {
 				uploadFile(imgName ,function(err) {
					loop++;
 					wayneCallback(err)
 				});
 			})
 			request
 				.get(url)
 				.on('respone', function(response) {
 					console.log(loop +'----' +response.statusCode)
 				})
 				.pipe(writer)
 				.on('error', function(err) {
 					console.log('err'+ err);
 				})
 		},
 		function(err) {
 			callback(err, {
 				successImg: successImg,
 				successCount: successCount
 			});
 		}
 	)
}


exports.upImgToUpyun=function(imgName,dest,cb){
	var upyun = new UPYUN(upyunConfig.bucket, upyunConfig.operator,
		upyunConfig.password, upyunConfig.endpoint, upyunConfig.apiVersion);
	var loop = 0;
	var type = 'imgae/jpg';
	var remotePath = dest + '/' + imgName;
	var localFile = './uploads/code/' + imgName;
	upyun.uploadFile(remotePath, localFile, type, true, {mkdir: true}, function(err, data) {
		if (err) {
			console.log(err);
			cb(err);
		} else {
			if (data.statusCode == 200) {
				//successCount++;
				//successImg.push(remotePath);
				//删除本地缓存文件
				fs.unlink(localFile,function(err,data){});
				cb(err,{url:remotePath});
			} else {
				console.log(data.error);
				cb({msg: data.error});
			}
		}
	})
}